from django.db.models import Q, F
from django.http.response import JsonResponse
from django.shortcuts import redirect, render, HttpResponse
from django.views.generic import View, ListView
from django.contrib.contenttypes.models import ContentType
from django.urls import reverse
from DjangoMall.views import BaseView
from dadmin.views import HasLoginRequired
from product.models.product import ProductSPU
from users.models.operate import DmallFavorite, DmallHotSearchWords
from users.forms import DmallFavoriteForm
from product.models import ProductSKU


# 文档：https://docs.djangoproject.com/zh-hans/3.2/topics/class-based-views/intro/#decorating-the-class

# @method_decorator(login_required(login_url='/users/login/'), name='dispatch')
class DmallFavoriteView(HasLoginRequired, View):
    """ 收藏 """
    def get(self, request, *args, **kwargs):
        fav_form = DmallFavoriteForm()
        return render(request, 'users/fav.html', {'fav_form': fav_form})

    def post(self, request, *args, **kwargs):
        fav_form = DmallFavoriteForm(request.POST)
        object_id = request.POST['object_id']
        # content_type = request.POST['content_type']
        content_type = ContentType.objects.get_for_model(ProductSKU)
        data = DmallFavorite.objects.filter(content_type=content_type, object_id=object_id)
        
        if data.exists():
            data.delete()
            # return redirect(reverse('goods:goods-detail', kwargs={'pk': object_id})) 
            return JsonResponse({'message': '已取消收藏'})
        elif fav_form.is_valid():
            new_fav = fav_form.save(commit=False)
            new_fav.owner = request.user
            new_fav.content_type = content_type
            new_fav.save()
            # return redirect(reverse('goods:goods-detail', kwargs={'pk': object_id})) 
            return JsonResponse({'message': '收藏成功'})
        return render(request, 'goods/goods_fav.html', {'fav_form': fav_form})


class DmallSearchView(BaseView, ListView):
    """ 搜索视图"""
    template_name = 'users/search.html'
    context_object_name = 'spus'

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['keyword'] = self.request.GET.get('keyword', '')       # 搜索词 
        context['hotwords'] = DmallHotSearchWords.objects.all()[:10]   # 热搜词
        return context

    def get_queryset(self):
        # 重写queryset
        queryset = ProductSPU.objects.filter(is_del=False, is_show=True, is_release=True)
        keyword = self.request.GET.get('keyword')
        if not keyword:
            return queryset
        else:
            queryset = queryset.filter(Q(title__icontains=keyword) | Q(sub_title__icontains=keyword) | Q(desc__icontains=keyword))
            for product in queryset:
                if product.spec_type == 1:
                    sku = product.skus.filter(is_del=False, is_show=True).first()
                    product.shop_price = sku.shop_price
                    product.market_price = sku.market_price
                    product.cost_price = sku.cost_price
                    product.stock = sku.stock
            return queryset